package com.rongc.client.freight.business.supply.view.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.View;

import com.android.volley.Response;
import com.android.volley.error.VolleyError;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.rongc.client.core.gson.GsonHelper;
import com.rongc.client.core.network.code.HandleCode;
import com.rongc.client.core.network.http.RequestManager;
import com.rongc.client.core.utils.ActivityUtils;
import com.rongc.client.core.utils.StringUtils;
import com.rongc.client.freight.ApiUrl;
import com.rongc.client.freight.R;
import com.rongc.client.freight.UniApplication;
import com.rongc.client.freight.base.BaseActivity;
import com.rongc.client.freight.base.view.widget.BGASortableNinePhotoLayoutView;
import com.rongc.client.freight.business.carrier.model.ConveyanceBean;
import com.rongc.client.freight.business.carrier.request.api.ConveyanceDetailApi;
import com.rongc.client.freight.business.mine.model.CarBean;
import com.rongc.client.freight.business.mine.view.activity.AuthHostActivity;
import com.rongc.client.freight.business.supply.model.CommentBean;
import com.rongc.client.freight.business.supply.request.api.SupplyHasList2MatchApi;
import com.rongc.client.freight.business.supply.view.fragment.AddressFragment;
import com.rongc.client.freight.business.supply.view.fragment.SupplyCommentListFragment;
import com.rongc.client.freight.business.supply.view.fragment.SupplyDetailFragment;
import com.rongc.client.freight.business.supply.view.fragment.UserFragment;
import com.rongc.client.freight.business.waybill.request.api.WaybillCreateApi;
import com.rongc.client.freight.business.waybill.view.activity.WayBillNewActivity;
import com.rongc.client.freight.utils.UtilMethod;
import com.viewpagerindicator.TabPageIndicator;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPreviewActivity;

import static com.flyco.dialog.widget.NormalDialog.STYLE_ONE;
import static com.flyco.dialog.widget.NormalDialog.STYLE_TWO;
import static com.rongc.client.freight.business.supply.model.SupplyDic.StatusType.YAJIN_STATUS;

/**
 * Created by Bruce on 2017/7/7.
 */
public class SupplyConveyanceDetailActivity extends BaseActivity implements View.OnClickListener, BGASortableNinePhotoLayoutView.Delegate{
    private static final String[] CONTENT = new String[] { "车辆详情", "货主评价"};

    @Bind(R.id.pager)
    ViewPager pager;
    @Bind(R.id.indicator)
    TabPageIndicator indicator ;

    FragmentPagerAdapter adapter;
    SupplyDetailFragment mYJSFragment;
    SupplyCommentListFragment mWJSFragment;
    List<Fragment> mFragments = new ArrayList<Fragment>();

    UserFragment userFragment;
    AddressFragment addressFragment;

    String supplyId;
    String price;
    ConveyanceBean conveyanceBean;
    CarBean carBean;
    List<CommentBean> commentBeanList;

    String waybillId;

    @Bind(R.id.activity_discover_invest_publish_nine_photo)
    BGASortableNinePhotoLayoutView ninePhotoLayout;
    ArrayList<String> selectedPhotos = new ArrayList<>();

    NormalDialog dialog;
    NormalDialog payDialog;
    NormalDialog authDialog;


    @OnClick({R.id.btn_submit})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_submit:
                if(UniApplication.getInstance().isAuth()) {
                    String number = conveyanceBean.getPhone();
                    ActivityUtils.callTo(this,number,dialog);

                }else{
                    doAuth();
                }
                break;

        }
    }

    @Override
    public void onAuth() {
        if(UniApplication.getInstance().isAuth()) {
            String number = conveyanceBean.getPhone();
            ActivityUtils.callTo(this,number,dialog);
        }else{
            if(UniApplication.getInstance().isAuthIng())
                ActivityUtils.toast("您已提交申请，还在审核当中");
            else
                authDialog.show();
        }
    }

    Response.Listener<JSONObject> respDetailListener = new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            if (HandleCode.requestSuccess()) {
                try {
                    conveyanceBean = GsonHelper.getDeserializer().fromJson(response.getString("trucksInfo"), ConveyanceBean.class);
                    carBean = GsonHelper.getDeserializer().fromJson(response.getString("driverInfo"), CarBean.class);
                    CommentBean[] commenta = GsonHelper.getDeserializer().fromJson(response.getString("replayList"), CommentBean[].class);
                    commentBeanList.clear();
                    if(commenta != null)
                    for (int i=0;i<commenta.length;i++){
                        commentBeanList.add(commenta[i]);
                    }

                    mYJSFragment.setData(conveyanceBean,carBean);
                    mWJSFragment.setDatas(commentBeanList);

                    userFragment.setData(conveyanceBean.getImage(),conveyanceBean.getNick(),
                            response.optString("xiadanNumber"),response.optString("jiedanNumber"),
                            response.optJSONObject("rateInfo").optString("rate"),conveyanceBean.getPhone());
                    userFragment.hidePhone();
                    addressFragment.setData(conveyanceBean);

                    if(StringUtils.isNotEmpty(carBean.getImg2()))
                        selectedPhotos.add(ApiUrl.getCarImgUrl(carBean.getImg2()));
                    if(StringUtils.isNotEmpty(carBean.getImg3()))
                        selectedPhotos.add(ApiUrl.getCarImgUrl(carBean.getImg3()));
                    if(StringUtils.isNotEmpty(carBean.getImg4()))
                        selectedPhotos.add(ApiUrl.getCarImgUrl(carBean.getImg4()));
//                    if(StringUtils.isNotEmpty(carBean.getImg4()))
//                        selectedPhotos.add(carBean.getImg4());
                    ninePhotoLayout.setData(selectedPhotos);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                UtilMethod.dismissProgressDialog(SupplyConveyanceDetailActivity.this);
            }
        }
    };

    Response.Listener<JSONObject> respCreateListener = new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            if (HandleCode.requestSuccess()) {
                waybillId = response.optString("id");
//                payDialog.show();

                Bundle bundle = new Bundle();
                bundle.putString("data",waybillId);
                bundle.putInt("status",YAJIN_STATUS);
                ActivityUtils.startActivity(SupplyConveyanceDetailActivity.this, WayBillNewActivity.class,bundle);

            } else {
                UtilMethod.dismissProgressDialog(SupplyConveyanceDetailActivity.this);
            }
        }
    };

    Response.Listener<JSONObject> respMatchListener = new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            if (HandleCode.requestSuccess()) {
                String status = response.optString("status");
                if("1".equals(status)){
                    //  进入列表
                    Bundle bundle = new Bundle();
                    bundle.putString("conveyanceId", conveyanceBean.getId());
                    ActivityUtils.startActivity(SupplyConveyanceDetailActivity.this, SupplyList2MatchActivity.class,bundle);
                }else{
                    Bundle bundle = new Bundle();
                    bundle.putString("conveyanceId", conveyanceBean.getId());
                    ActivityUtils.startActivity(SupplyConveyanceDetailActivity.this, SupplyCreateActivity.class,bundle);
                }
                finish();
            } else {
                UtilMethod.dismissProgressDialog(SupplyConveyanceDetailActivity.this);
            }
        }
    };

    Response.ErrorListener errorListener = new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            UtilMethod.dismissProgressDialog(SupplyConveyanceDetailActivity.this);
        }
    };


    @Override
    public void initData() {

        ConveyanceDetailApi p = new ConveyanceDetailApi(new ConveyanceDetailApi.ConveyanceDetailParams(
                conveyanceBean.getTrucksId(),conveyanceBean.getId()),
                respDetailListener, errorListener);
        RequestManager.getInstance().call(p);
    }

    @Override
    public void initParams() {
        conveyanceBean = (ConveyanceBean) getIntent().getSerializableExtra("data");
        supplyId = getIntent().getStringExtra("supplyId");
        price = getIntent().getStringExtra("price");
    }

    @Override
    public void initView() {
        initToolbar(R.string.supply_conveyance_detail_title);
        commentBeanList = new ArrayList<>();
        selectedPhotos = new ArrayList<>();

        ninePhotoLayout.init(this);
        ninePhotoLayout.setDelegate(this);

        userFragment = (UserFragment) getSupportFragmentManager().findFragmentByTag("user");
        addressFragment = (AddressFragment) getSupportFragmentManager().findFragmentByTag("address");

        if(mFragments != null && mFragments.size() == 0){
            mYJSFragment = SupplyDetailFragment.getInstance();
            mWJSFragment = SupplyCommentListFragment.getInstance();
            mFragments.add(mYJSFragment);
            mFragments.add(mWJSFragment);
        }

        adapter = new GoogleMusicAdapter(getSupportFragmentManager());
        pager.setAdapter(adapter);
        pager.setOffscreenPageLimit(2);

        indicator.setVisibility(View.VISIBLE);
        indicator.setViewPager(pager);

        makeDialog();
        makePayDialog();
        makeAuthDialog();
    }


    void makeDialog(){
        dialog = new NormalDialog(this);
        dialog.isTitleShow(false)
                .content("是否发单给该车主")
                .contentGravity(Gravity.CENTER)
                .style(STYLE_ONE)
                .btnText(new String[]{"取消","确认"})
                .setOnBtnClickL(new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.cancel();
                    }
                },new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        if(StringUtils.isEmpty(supplyId)) {
                            // 从找车界面进来，不绑定货源

                            SupplyHasList2MatchApi p = new SupplyHasList2MatchApi(new SupplyHasList2MatchApi.SupplyHasList2MatchParams(),
                                    respMatchListener, errorListener);
                            RequestManager.getInstance().call(p);

                        }else{
                            //  绑定货源
                            WaybillCreateApi p = new WaybillCreateApi(new WaybillCreateApi.WaybillCreateParams(
                                    conveyanceBean.getId(),supplyId,price),
                                    respCreateListener, errorListener);
                            RequestManager.getInstance().call(p);
                        }
                        dialog.cancel();
                    }
                });
    }

    void makePayDialog(){
        payDialog = new NormalDialog(this);
        payDialog.content("线上支付送货物保险，为了保障您的货物安全，请线上支付。")
                .style(STYLE_TWO)
                .btnText(new String[]{"取消","支付"})
                .setOnBtnClickL(new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        payDialog.cancel();
                    }
                },new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        Bundle bundle = new Bundle();
                        bundle.putString("data",waybillId);
                        bundle.putInt("status",YAJIN_STATUS);
                        ActivityUtils.startActivity(SupplyConveyanceDetailActivity.this, WayBillNewActivity.class,bundle);
                        payDialog.cancel();
                        finish();
                    }
                });
    }

    void makeAuthDialog(){
        authDialog = new NormalDialog(this);
        authDialog.title(getResources().getString(R.string.auth_dialog_title))
                .content(getResources().getString(R.string.auth_contact_label))
                .style(STYLE_TWO)
                .btnText(new String[]{"取消","立即认证"})
                .setOnBtnClickL(new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        authDialog.cancel();
                    }
                },new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        ActivityUtils.startActivity(SupplyConveyanceDetailActivity.this, AuthHostActivity.class);
                        authDialog.cancel();
                    }
                });
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_supply_conveyance_detail;
    }


    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayoutView ninePhotoLayout, View view, int position, String model, List<String> models) {
        startActivity(BGAPhotoPreviewActivity.newIntent(this, null, (ArrayList<String>) models, position));
    }

    @Override
    public boolean onLongClickNinePhotoItem(BGASortableNinePhotoLayoutView ninePhotoLayout, View view, int position, String model, List<String> models) {
        return false;
    }

    class GoogleMusicAdapter extends FragmentPagerAdapter {
        public GoogleMusicAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    if(mYJSFragment == null)
                        mYJSFragment = SupplyDetailFragment.getInstance();
                    return mYJSFragment;
                case 1:
                    if(mWJSFragment == null) {
                        mWJSFragment = SupplyCommentListFragment.getInstance();
                    }
                    return mWJSFragment;
                default:
                    break;
            }

            return mFragments.get(position);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return CONTENT[position % CONTENT.length].toUpperCase();
        }

        @Override
        public int getCount() {
            return CONTENT.length;
        }
    }
}
